package light.head.controller.el;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.el.AnswerRecordDAO;
import light.head.dao.el.ClassesCourseRelationDAO;
import light.head.dao.el.ClassesDAO;
import light.head.dao.el.ExamRecordDAO;
import light.head.dao.el.LearnDAO;
import light.head.dao.el.PaperTemplateItemDAO;
import light.head.dao.el.TopicAnswerDAO;
import light.head.dao.el.TopicDAO;
import light.head.dao.el.TopicRecordDAO;
import light.head.dao.el.TrainDataAnnexDAO;
import light.head.dao.el.TrainDataDAO;
import light.head.dao.sys.FileDAO;
import light.head.dto.ExamTopic;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.framework.utils.DownLoadUtils;
import light.head.model.FileInfo;
import light.head.model.el.AnswerRecord;
import light.head.model.el.Classes;
import light.head.model.el.ClassesCourseRelation;
import light.head.model.el.ClassesCourseRelationPK;
import light.head.model.el.ExamRecord;
import light.head.model.el.Learn;
import light.head.model.el.PaperTemplateItem;
import light.head.model.el.TopicAnswer;
import light.head.model.el.TopicRecord;
import light.head.model.el.TrainData;
import light.head.model.el.TrainDataAnnex;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(Url.C_MYCLASS)
public class MyClassController extends SupporterController {
	/**
	 * 我的班级
	 */
	
	private final static String upload_path = "upload/data/";
	private ClassesDAO classesDAO;
	private ClassesCourseRelationDAO ccrDAO;
	private TrainDataDAO materialDAO;
	private TrainDataAnnexDAO maDAO;
	private TopicDAO topicDAO;
	private PaperTemplateItemDAO tempItemDAO;
	private ExamRecordDAO examRecordDAO;
	private TopicAnswerDAO topicKeyDAO;
	private TopicRecordDAO trDAO;
	private AnswerRecordDAO arDAO;
	private LearnDAO learnDAO;
	private FileDAO fDAO;
	
	
	@RequestMapping(Url.INIT)
	public ModelAndView init(HttpServletRequest request, HttpServletResponse response){
		return new ModelAndView(Url.MYCLASS_INIT);
	}
	
	
	@RequestMapping(Url.QUERY)
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response){
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.NAME,Parm.DELETED);
		if(classesDAO.findByMap1(cu_code(request), map, pb) == RESULT.SUCCESS){
			Classes cs = null;
			for (Object o : pb.getResultList()) {
				cs = (Classes) o;
				cs.setCcrList(ccrDAO.findByCcrCode(cs.getCode()));
			}
		}
		request.setAttribute(Parm.PAGE_BEAN, pb);
		return new ModelAndView(Url.MYCLASS_LIST);
	}
	
	
	//显示培训资料和考试
	@RequestMapping("showMaterialAndExam")
	public ModelAndView showMaterialAndExam(HttpServletRequest request, HttpServletResponse response){
		String classCode = request.getParameter("code");		//班级编号
		String courseCode = request.getParameter("cc");			//课程编号
		if(isNotNull(classCode) && isNotNull(courseCode)){
			
			//判断是否可考试
			Boolean isExam = false;
			ClassesCourseRelationPK pk = new ClassesCourseRelationPK();
			pk.setCc(Integer.parseInt(courseCode));
			pk.setClc(Integer.parseInt(classCode));
			Classes c = ccrDAO.hql_findByClc(pk.getClc());
			ClassesCourseRelation ccr = ccrDAO.get(pk);
			//获取培训资料
			List<TrainData> tmList = materialDAO.findByCc(Integer.parseInt(courseCode));
			for(TrainData tm : tmList){
				List<TrainDataAnnex> list = maDAO.findByTmc(tm.getCode());
				for (TrainDataAnnex t : list) {
					t.setTotal(learnDAO.findByClcAndCc(t.getCode(),Integer.parseInt(classCode),Integer.parseInt(courseCode),cu_code(request)));
				}
				tm.setList(list);
				//学习情况
			}
			List<Learn> learn = learnDAO.findByClcAndUcAndCc(Integer.parseInt(classCode),cu_code(request),ccr.getCc());
			Date time =new Date();
			if(c.getBeginTime() != null && c.getBeginTime().getTime() <= time.getTime() && time.getTime() <= c.getFinishTime().getTime()){
				isExam = true;
			}
			//判断是否有未阅卷的
			Integer isMarke = 1;
			List<ExamRecord> exlist = examRecordDAO.findByClcUcCc(pk.getClc(), cu_code(request), pk.getCc());
			if (exlist != null && exlist.size() > 0){
				isMarke = 2;
			}
			//判断是否有通过的
			Integer isPass = 1;
			List<ExamRecord> eclist = examRecordDAO.findByClcUcCc(pk.getClc(), cu_code(request), pk.getCc());
			if (eclist != null && eclist.size() > 0){
				isPass = 2;
			}
			//获取考试记录
			List<ExamRecord> erList = examRecordDAO.findByClcAndUcAndCc(pk.getClc(), cu_code(request), pk.getCc());
			request.setAttribute("isPass", isPass);			//是否有通过的
			request.setAttribute("isMarke", isMarke);			//是否有需要阅卷却未阅卷的
			request.setAttribute("courseCode", courseCode);
			request.setAttribute("classCode", classCode);
			request.setAttribute("tmList", tmList);
			request.setAttribute("learn", learn);			//培训资料
			request.setAttribute("isExam", isExam);			//是否可考试
			request.setAttribute("erList", erList);			//考试记录
			request.setAttribute("ccr", ccr);
			request.setAttribute("c", c);
		}
		return new ModelAndView(Url.MYCLASS_EDIT);
	}
	
	@Transactional
	@RequestMapping(value = Url.DOWNLOAD)
	public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
		}
		FileInfo fi = fDAO.getByUuid(code);
		TrainDataAnnex d = maDAO.getByUuid(code);
		if (null == fi) {
		}
		DownLoadUtils.downLoad(upload_path, d.getName(), fi.getUuid(), fi.getExt(), response);
	}
	
	@RequestMapping("learnMaterialAnnex")
	public ModelAndView learnMaterialAnnex(HttpServletRequest request, HttpServletResponse response){
		String clc = request.getParameter("clc");
		String cc = request.getParameter("cc");
		String tmc = request.getParameter("tmc");
		String tmac = request.getParameter("tmac");
		if(isNotNull(clc) && isNotNull(cc) && isNotNull(tmc) && isNotNull(tmac)){
			Learn learn = learnDAO.getOne(Integer.parseInt(clc), Integer.parseInt(cc), Integer.parseInt(tmc), Integer.parseInt(tmac), cu_code(request));
			if(learn != null){
				request.setAttribute("loadPage", learn.getPage());
			}
		}
		request.setAttribute("clc", clc);
		request.setAttribute("cc", cc);
		request.setAttribute("tmc", tmc);
		request.setAttribute("tmac", tmac);
		request.setAttribute("learnUrl", request.getParameter("learnUrl"));
		return new ModelAndView(Url.MYCLASS_LEARNMATERIALANNEX);
	}

	//开始考试
	@RequestMapping(Url.EXAM)
	public ModelAndView exam(HttpServletRequest request, HttpServletResponse response){
		String classCode = request.getParameter("classCode");			//班级编号
		String courseCode = request.getParameter("courseCode");			//课程编号
		if(isNotNull(classCode) && isNotNull(courseCode)){
			Integer clc = Integer.parseInt(classCode);
			Integer cc = Integer.parseInt(courseCode);
			ClassesCourseRelationPK ccrPK = new ClassesCourseRelationPK();
			ccrPK.setCc(cc);
			ccrPK.setClc(clc);
			ClassesCourseRelation ccr = ccrDAO.get(ccrPK);
			Boolean a = false;
			if(ccr != null){
				ExamRecord er = new ExamRecord();
				List<ExamTopic> etList = topicDAO.getExamByClcAndCc(clc, cc);//已指定的题目
				if(ccr.getTtc() != null){//有模板
					List<ExamTopic> list = null;		//接收系统自选题目
					if(etList != null && etList.size() > 0){//有指定题
						List<PaperTemplateItem> tempList = tempItemDAO.findByClcAndTtcAndCc(clc, ccr.getTtc(), cc);
						if(tempList != null && tempList.size() > 0){
							list = topicDAO.getExamByTempItem(cc, tempList);
						}
						if(list != null && list.size() > 0){
							etList.addAll(list);
						}
						topicKeyDAO.addTopicKey(etList);
						for (ExamTopic t : etList) {
							if(t.getType() == 1 || t.getType() == 2){
								er.setIsMark(true);
							}
						}
						request.setAttribute(Parm.LIST, topicDAO.px(etList));
					}else{//无指定题
						List<PaperTemplateItem> tempList = tempItemDAO.findByTtc(ccr.getTtc()); //得到模板明细
						if(tempList != null && tempList.size() > 0){
							list = topicDAO.getExamByTempItem(cc, tempList);
						}
						if (list != null && list.size() != 0){
							topicKeyDAO.addTopicKey(list);
							for (ExamTopic t : list) {
								if(t.getType() == 3 ){
									er.setIsMark(true);
								}
							}
							request.setAttribute(Parm.LIST, topicDAO.px(list));
						}else{
							a = true;
						}
					}
				}else{//无模板
					topicKeyDAO.addTopicKey(etList);
					for (ExamTopic t : etList) {
						if(t.getType() == 3 ){
							er.setIsMark(true);
						}
					}
					request.setAttribute(Parm.LIST, topicDAO.px(etList));
				}
				//添加考试纪录
				if (a == false){
					Date ct = new Date();
					er.setClc(clc);
					er.setCc(cc);
					er.setExamScore(0f);
					//er.setIsPass(false);
					er.setCt(ct);
					er.setOc(cu_organCode(request));
					er.setCu(cu_code(request));
					er.setDeleted(false);
					examRecordDAO.add(er);
					
				}
				request.setAttribute("er", er);
				request.setAttribute("ccr", ccr);
				request.setAttribute("a", a);
			}
		}
		return new ModelAndView(Url.MYCLASS_EXAM);
	}
	
	@RequestMapping("saveExam")
	@Transactional(rollbackFor = Exception.class)
	public void saveExam(ExamRecord er, HttpServletRequest request, HttpServletResponse response) throws Exception{
		Float total = 0f;	//总得分
		Boolean look = false;
		String result = null;
		if(er.getCode() != null){
			List<TopicRecord> trList = er.getTrList();
			for(TopicRecord tr : trList){
				if(tr != null && tr.getTc() != null){
					if(tr.getType().byteValue() == Sys.B_THREE){
						look = true;
					}
					tr.setErc(er.getCode());
					tr.setOc(cu_organCode(request));
					tr.setCu(cu_code(request));
					tr.setDeleted(false);
					tr.setPoint(0f);
					List<AnswerRecord> arList = tr.getArList();
					if(arList != null && arList.size() > 0){
						if(tr.getType().byteValue() == Sys.B_ONE){
							List<TopicAnswer> tkList = topicKeyDAO.findKeyisRight(tr.getTc());
							if(tkList != null && tkList.size() > 0){
								if(tkList.get(0).getCode().intValue() == arList.get(0).getAnswerCode().intValue()){
									tr.setPoint(tr.getPoints());
									total += tr.getPoints();
								}
							}
						}else if(tr.getType().byteValue() == Sys.B_TWO){
							List<TopicAnswer> tkList = topicKeyDAO.findKeyisRight(tr.getTc());
							if(arList.size() == tkList.size()){
								int i = 0;
								for(TopicAnswer tk : tkList){
									for(AnswerRecord ar : arList){
										if(ar.getAnswerCode() != null && tk.getCode().intValue() == ar.getAnswerCode().intValue()){
											i++;
										}
									}
								}
								if(i == tkList.size()){
									tr.setPoint(tr.getPoints());
									total += tr.getPoints();
								}
							}
						}
					}
					if(trDAO.add(tr) == RESULT.SUCCESS){
						if(arList != null && arList.size() > 0){
							for(AnswerRecord ar : arList){
								ar.setTrc(tr.getCode());
								ar.setErc(er.getCode());
								ar.setTc(tr.getTc());
								arDAO.add(ar);
							}
						}
					}
				}
			}
			er = examRecordDAO.get(er.getCode());
			er.setExamScore(total);
			er.setIsMark(look);
			examRecordDAO.upd(er);
		}
		if(look){
			result = "{\"result\":\"success_look\" ," +
					" \"total\":\""+ total +"\"" +
					"}";
			print(response, result);
		}else{
			result = "{\"result\":\"success\" ," +
					" \"total\":\""+ total +"\"" +
					"}";
			print(response, result);
		}
	}
	
	//记录学习情况
	@RequestMapping("saveLearn")
	public void saveLearn(HttpServletRequest request, HttpServletResponse response){
		String clc = request.getParameter("clc");
		String cc = request.getParameter("cc");
		String tmc = request.getParameter("tmc");
		String tmac = request.getParameter("tmac");
		String page = request.getParameter("page");
		String learnTime = request.getParameter("learnTime");
		if(isNotNull(clc) && isNotNull(cc) && isNotNull(tmc) && isNotNull(tmac)){
			Learn learn = learnDAO.getOne(Integer.parseInt(clc), Integer.parseInt(cc), Integer.parseInt(tmc), Integer.parseInt(tmac), cu_code(request));
			if(learn != null){
				if(isNotNull(learnTime)){
					learn.setTime((long)(learn.getTime() + Integer.parseInt(learnTime)));
				}
				if(isNotNull(page)){
					learn.setPage(Integer.parseInt(page));
				}
				learnDAO.upd(learn);
			}else{
				learn = new Learn();
				learn.setClc(Integer.parseInt(clc));
				learn.setCc(Integer.parseInt(cc));
				learn.setTmc(Integer.parseInt(tmc));
				learn.setTmac(Integer.parseInt(tmac));
				learn.setCu(cu_code(request));
				learn.setTime(isNotNull(learnTime) ? Long.parseLong(learnTime) : 0);
				learn.setPage(isNotNull(page) ? Integer.parseInt(page) : null);
				learn.setDeleted(false);
				learnDAO.add(learn);
			}
		}
	}
	
	//查看考试记录
	@RequestMapping("openExamRecord")
	public ModelAndView openExamRecord(HttpServletRequest request, HttpServletResponse response){
		String code = request.getParameter(Parm.CODE);
		if(isNotNull(code)){
			ExamRecord er = examRecordDAO.get(Integer.parseInt(code));
			Byte a = classesDAO.findClc(er.getClc());
			request.setAttribute(Parm.A, a);
			if (a != null && a == 1){
				List<ExamTopic> list = topicDAO.findByErc(Integer.parseInt(code));
				arDAO.addAnswerRecordByErc(er.getCode(), list);
				topicKeyDAO.addTopicKey(list);
				request.setAttribute("er", er);
				request.setAttribute(Parm.LIST, list);
			}else{
				List<TopicRecord> trList = trDAO.findByErc(Integer.parseInt(code));
				if(trList != null && trList.size() > 0){
					for(TopicRecord tr : trList){
						List<AnswerRecord> list = arDAO.findByTrcAndErcAndTc(tr.getCode(), Integer.parseInt(code), tr.getTc());
						tr.setArList(list);
						tr.setTopic(topicDAO.get(tr.getTc()));
						if(tr.getTopic() != null){
							tr.getTopic().setItemList(topicKeyDAO.findKeyByCode(tr.getTopic().getCode()));
						}
					}
				}
				request.setAttribute(Parm.INFO, er);
				request.setAttribute(Parm.TRLIST, trList);
			}
			
		}
		return new ModelAndView(Url.MYCLASS_EXAMRECORD);
	}

	
	@Autowired
	public void setClassesDAO(ClassesDAO classesDAO) {
		this.classesDAO = classesDAO;
	}
	@Autowired
	public void setCcrDAO(ClassesCourseRelationDAO ccrDAO) {
		this.ccrDAO = ccrDAO;
	}
	@Autowired
	public void setTopicDAO(TopicDAO topicDAO) {
		this.topicDAO = topicDAO;
	}
	@Autowired
	public void setMaterialDAO(TrainDataDAO materialDAO) {
		this.materialDAO = materialDAO;
	}
	@Autowired
	public void setMaDAO(TrainDataAnnexDAO maDAO) {
		this.maDAO = maDAO;
	}
	@Autowired
	public void setTempItemDAO(PaperTemplateItemDAO tempItemDAO) {
		this.tempItemDAO = tempItemDAO;
	}
	@Autowired
	public void setTopicKeyDAO(TopicAnswerDAO topicKeyDAO) {
		this.topicKeyDAO = topicKeyDAO;
	}
	@Autowired
	public void setExamRecordDAO(ExamRecordDAO examRecordDAO) {
		this.examRecordDAO = examRecordDAO;
	}
	@Autowired
	public void setTrDAO(TopicRecordDAO trDAO) {
		this.trDAO = trDAO;
	}
	@Autowired
	public void setArDAO(AnswerRecordDAO arDAO) {
		this.arDAO = arDAO;
	}
	@Autowired
	public void setLearnDAO(LearnDAO learnDAO) {
		this.learnDAO = learnDAO;
	}

	@Autowired
	public void setfDAO(FileDAO fDAO) {
		this.fDAO = fDAO;
	}

}
